package logger

import (
	"fmt"
	"os"
	"strings"
	"time"
)

// ConsoleLogger 控制台日志
type ConsoleLogger struct {
	logLevel LogLevel
}

// NewConsoleLogger 构造函数
func NewConsoleLogger(logLevel LogLevel) *ConsoleLogger {
	return &ConsoleLogger{
		logLevel: logLevel,
	}
}

func (c *ConsoleLogger) writelog(logLevel string, format string, a ...interface{}) {
	if !c.enable(logLevel) {
		return
	}
	formatStr := fmt.Sprintf(format, a...)
	msg := fmt.Sprintf("[%s] %s %s", time.Now().Format("2006-01-02 15:04:05"), logLevel, formatStr)
	fmt.Fprintln(os.Stdout, msg)
}

// Trace 级别日志跟踪
func (c *ConsoleLogger) Trace(format string, a ...interface{}) {
	c.writelog("TRACE", format, a...)
}

// Debug 级别日志跟踪
func (c *ConsoleLogger) Debug(format string, a ...interface{}) {
	c.writelog("DEBUG", format, a...)
}

// Warning 级别日志跟踪
func (c *ConsoleLogger) Warning(format string, a ...interface{}) {
	c.writelog("WARNING", format, a...)
}

// Info 级别日志跟踪
func (c *ConsoleLogger) Info(format string, a ...interface{}) {
	c.writelog("INFO", format, a...)
}

// Error 级别日志跟踪
func (c *ConsoleLogger) Error(format string, a ...interface{}) {
	c.writelog("ERROR", format, a...)
}

// 是否开启当前级别的日志
func (c *ConsoleLogger) enable(logLevel string) bool {
	switch strings.ToUpper(logLevel) {
	case "TRACE":
		return LevelTrace >= c.logLevel
	case "DEBUG":
		return LevelDebug >= c.logLevel
	case "INFO":
		return LevelInfo >= c.logLevel
	case "WARNING":
		return LevelWarning >= c.logLevel
	case "ERROR":
		return LevelError >= c.logLevel
	default:
		return LevelInfo >= c.logLevel
	}
}
